<?php
/**
 * Created by PhpStorm.
 * 物流系统业务处理
 * User: caicm
 * Date: 2017/7/3
 * Time: 13:29
 */

namespace WMApi\Service;


use WMApi\Model\WmOrderActionModel;
use WMApi\Model\WmOrderGoodsModel;
use WMApi\Model\WmOrderInfoModel;

class BscService {

    protected $store_no = '1851324047';
    protected $sign_method = 'md5';
    protected $app_key = 'cJM096wA';
    protected $app_secret = 'XODiTZLhEJrbpe1xFE3yePdQ3zRkFqUw';
    protected $post_url = 'http://bsc.test.shidexian.com/index.php?s=/Open/Order/';
    protected $data = array();

    public function __construct(){
        $time = time();
        $sign = strtoupper(md5($this->store_no . $time . $this->sign_method . $this->app_secret . substr($time, -1)));
        //公共参数
        $this->data =array(
            'time' => $time,
            'store_no' => $this->store_no,
            'sign_method' => $this->sign_method,
            'app_key' => $this->app_key,
            'app_secret' => $this->app_secret,
            'sign' => $sign,
        );
    }

    /**
     * 物流配送回调处理业务
     * Created By caicm
     * @param string $order_sn 订单号
     * @param string $contact 操作者姓名
     * @param int $phone 操作者电话
     * @param int $op_time 操作时间
     * @param int $best_time 延迟订单时间
     * @param int $op_type
     * @param string $sign
     * @param string $remark
     * @return bool
     */
    public function bsc_notice($order_sn='', $contact='', $phone=0, $op_time=0, $best_time=0, $op_type=0, $sign='', $remark=''){
        $bsc_sign = strtoupper(md5($this->app_secret.$this->app_key.$this->store_no.$order_sn.$op_type.$op_time.substr($op_time, -1)));
        if($bsc_sign != $sign){
            returnApiError('签名有误！'.$bsc_sign);
        }

        //物流系统-订单查询
        $bsc_order = $this->select_order_status($order_sn);
        if($bsc_order['status'] != 1){
           returnApiError('物流接口有误');
        }

        $bsc_data = explode('-', $bsc_order['now_status_code']);
        $trunk_line_status = $bsc_data[0];
        $tail_end_status = $bsc_data[1];

        $action_model = new WmOrderActionModel();
        $order_model = new WmOrderInfoModel();
        $action_model->startTrans();

        //订单详情
        $order_info = $order_model->find_orderinfo_by_id(0, $order_sn);
        if(!$order_info){
            returnApiError('订单不存在');
        }

        $created = "【{$contact}-{$phone}】";
        $op_time = timetogmtime($op_time);

        /**
         * 写入订单操作记录
         */
        $add_action = $action_model->add_action($order_info['seller_id'], $order_info['store_id'], $order_info['order_id'], $remark, $created, $order_info['order_status'], $order_info['seller_status'], $trunk_line_status, $tail_end_status, $op_type);


        //状态-已接单
        if($tail_end_status == 2){
            $data['shipping_confirm_time'] = $op_time;          //配送接单时间
            $data['courier_name'] = $contact;                   //配送员姓名
            $data['courier_phone'] = $phone;                    //配送员电话
        }

        //状态-配送中
        if($tail_end_status == 3){
            $data['shipping_time'] = $op_time;                  //配送时间
            $data['courier_name'] = $contact;                   //配送员姓名
            $data['courier_phone'] = $phone;                    //配送员电话
        }

        //状态-已送达
        if($tail_end_status == 4){
            $data['confirm_time'] = $op_time;                   //确认收货时间
        }

        $data['trunk_line_status'] = $trunk_line_status;        //干线状态（1-未出仓，2-已出仓，3-已到站，4-已出站，5-已回站，6-需回仓，7-已离站，8-已回仓）
        $data['tail_end_status'] = $tail_end_status;            //末端状态（1-未接单，2-已接单，3-配送中，4已送达）
        $data['op_type'] = $op_type;                            //操作类型 1:[开始配送] 2:[完成配送] 3:[已到站] 4:[需回仓] 5:[延迟订单] 6:[配送退单] 7:[问题单] 8 司机揽件，9返回揽件 10：回仓确认
        $data['update_time'] = gmtime();

        /**
         * 修改订单配送状态
         */
        $update_shipping = $order_model->update_shipping_state($order_info['order_id'], $data);

        if($add_action && $update_shipping){
            $action_model->commit();
            return true;
        }else{
            $action_model->rollback();
            return false;
        }
    }

    /**
     * 推送订单
     * Created By caicm
     * @param int $order_id 订单id
     * @param int $scc_id 取货点id
     * @return string
     */
    public function post_order($order_id=0, $scc_id=0){
        $goods = array();
        $order_model = new WmOrderInfoModel();
        $goods_model = new WmOrderGoodsModel();
        $order_info = $order_model->find_orderinfo_by_id($order_id);
        if(!$order_info){
            returnApiError('订单不存在');
        }

        //商品列表
        $order_goods = $goods_model->find_order_goods_list($order_id);
        foreach ($order_goods as $key=>$val){
            $goods[$key] = array(
                'goods_name' => get_goods_name($val['goods_name'],$val['main_attr_value_name'],$val['sec_attr_value_name']),
                'goods_sn' => $val['goods_sn'],
                'goods_number' => $val['goods_number'],
                'goods_price' => $val['goods_price'],
                'goods_weight' => $val['goods_weight'],
            );
        }

        $order_data = array(
            'third_sn' => $order_info['order_sn'],
            'consignee' => $order_info['consignee'],
            'mobile' => $order_info['mobile'],
            'province' => $order_info['province_name'],
            'city' => $order_info['city_name'],
            'district' => $order_info['district_name'],
            'address' => $order_info['address'].$order_info['address_name'],
            'longitude' => $order_info['longitude'],
            'latitude' => $order_info['latitude'],
            'landmarks' => $order_info['sign_building'],
            'delivery_start_time' => localtotime($order_info['shipping_expect_time_start']),
            'delivery_end_time' => localtotime($order_info['shipping_expect_time_end']),
            'remark' => $order_info['postscript'],
            'goods' => json_encode($goods),
            'distribution_type' => $order_info['distribution_type'],
            'order_weight' => $order_info['order_weight'],
            'goods_num' => $order_info['goods_number'],
            'scc_id' => $scc_id
        );

        return $this->post_bsc('post_order', $order_data);

    }

    /**
     * 订单状态查询
     * Created By caicm
     * @param string $third_sn 订单号
     * @return string
     */
    public function select_order_status($third_sn=''){

        $data = array(
            'third_sn' => $third_sn,
        );

        return $this->post_bsc('select_order_status', $data);

    }

    /**
     * 获取所在地址的配送费用和配送时间
     * Created By caicm
     * @param $longitude 经度（必须）
     * @param $latitude 纬度（必须）
     * @param int $scc_id 取货点id
     * @param int $type 查询类型: 0-获取所有 1-配送时间 2-配送类型 3-配送费用
     * @param string $order_weight 订单重量
     * @param string $order_number 商品数量
     * @param string $year 年
     * @param string $month 月
     * @param string $day 日
     * @return string
     */
    public function get_order_freight_time($longitude, $latitude, $scc_id=0, $type=0, $order_weight='', $order_number='', $year='', $month='', $day=''){
        if(empty($year)){
            $year = date('Y');
        }
        if(empty($month)){
            $month = date('m');
        }
        if(empty($day)){
            $day = date('d');
        }

        $data = array(
            'longitude' => $longitude,
            'latitude' => $latitude,
            'scc_id' => $scc_id,
            'order_weight' => $order_weight,
            'order_number' => $order_number,
            'year' => $year,
            'month' => $month,
            'day' => $day,
            'type' => $type

        );


        return $this->post_bsc('get_order_freight_time', $data);

    }


    /**
     * 创建取货点
     * Created By caicm
     * @param string $longitude 经度（必须）
     * @param string $latitude 纬度（必须）
     * @param string $scc_name 取货点名称
     * @param string $province 省份
     * @param string $city 城市
     * @param string $district 区县
     * @param string $address 详细地址
     * @param int $radius 配送半径
     * @param string $remark 备注
     * @return string
     */
    public function add_scc($longitude='', $latitude='', $scc_name='', $province='', $city='', $district='', $address='', $radius=5, $remark=''){
        $data = array(
            'longitude' => $longitude,
            'latitude' => $latitude,
            'scc_name' => $scc_name,
            'province' => $province,
            'city' => $city,
            'district' => $district,
            'address' => $address,
            'radius' => $radius,
            'remark' => $remark,

        );

        return $this->post_bsc('add_scc', $data);

    }

    /**
     * 订单撤单
     * Created By caicm
     * @param string $third_sn 订单号
     * @return string
     */
    public function order_cancel($third_sn=''){
        $data = array(
            'third_sn' => $third_sn,
            'is_last_goods' => 1,
            'goods_list' => '',
        );

        return $this->post_bsc('order_cancel', $data);

    }




    /**
     * 发送到bsc物流系统
     * Created By caicm
     * @param string $url
     * @param array $order_data
     * @return string
     */
    protected function post_bsc($url='', $order_data=array()){
        $data = array_merge($this->data, $order_data);
        $res = http_post($this->post_url.$url, $data);
        return json_decode($res, true);
    }




}